 
const { Wechaty } = require('wechaty');
const config = require('./config.js');

class Robot{

    constructor(){
        this.bot = Wechaty.instance();
        this.initListener();
        this.bot.start()
    }

    static getInstance() {
        return this.instance || (this.instance = new this());
    }

    initListener() {

        // 获取二维码
        this.bot.on('scan', (url, code) => {  
            if (!/201|200/.test(String(code))){
               let loginUrl = url.replace(/\/qrcode\//, '/l/')
               require('qrcode-terminal').generate(loginUrl)  
            }  
            console.log(`${url}\n[${code}] Scan QR Code in above url to login: `)
        });

        // 监听登录
        this.bot.on('login', async user => {
            console.log(`User ${user} logined`)
            // console.log(this.bot.userSelf())            
            await this.initManager();
            await this.initRoom()
        });

        // 监听 有新消息
        this.bot.on('message', () => {
            // console.log(arguments)
        })

        // 监听 有好友申请 / 有好友同意申请
        this.bot.on('friendship', (friendship) => {
            receiveNewFriend(friendship);
        });

        // 监听 有人进群
        this.bot.on('room-join', (room, inviteeList, inviter) => {
            const nameList = inviteeList.map(c => c.name()).join(',')
            room.say(`欢迎 ${inviter} 同学邀请的 ${nameList} 入群`)
        });

        // 监听 有人离开群
        this.bot.on('room-leave', (room, inviteeList, inviter) => {
            const nameList = leaverList.map(c => c.name()).join(',')
            room.say(`${nameList} 同学离开了我们`)
        });

        // 监听 接到群邀请
        this.bot.on('room-invite', (roomInvitation) => {
            roomInvitation.accept()
        });
    }

    // 初始化管理员，根据配置表获取已和机器人添加好友的管理员
    async initManager() {
        this.managers = await Promise.all( 
            config.managers.map(manager =>  this.bot.Contact.find(manager))
        )
    }

    // 初始化群，根据配置表获取bot为群主的群数组，若不存在则创建群
    async initRoom() {
        this.rooms = await Promise.all(
            config.rooms.map(room => this.bot.Room.find(room))
        )
        console.log(this.rooms)
    }

    // 接受好友申请/好友同意申请
    async receiveNewFriend(friendship) {
        if(friendship.type() === this.bot.Friendship.Type.Receive){ // 1. receive new friendship request from new contact
            let contact = friendship.contact()
            let result = await friendship.accept()
            if(result){
                await contact.say('爸爸你好')
                this.addContactToRoom(false, contact)
                // console.log(`Request from ${contact.name()} is accept succesfully!`)
            } else{
                console.log(`添加好友 ${contact.name()} 失败`)
            }
        } else if (friendship.type() === Friendship.Type.Confirm) { // 2. confirm friendship
            await contact.say('爸爸你好')
            this.addContactToRoom(false, contact)
        }
    }

    // 创建群
    async createRoom(roomName, members) {
        // console.log('create')
        members = members || this.managers
        console.log(members)
        let room = await this.bot.Room.create(members)
        console.log('room:', room)
        console.log('roomName:', roomName)
        console.log('members:', members)
        await room.topic(`${roomName} - created`)
        await room.say(`${roomName} - created`)
        return room
    }

    // 添加联系人进群
    async addContactToRoom(room, contact) {
        let idx = 0;
        room = room || this.rooms[idx];
        try {
            await room.add(contact) 
        } catch { 
            ++idx;
            room = this.rooms[idx];
            room && await room.add(contact) 
        }
    }
}

let robot = Robot.getInstance()

module.exports = robot
